package com.eas.ereceipt.app;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.eas.ereceipt.R;
import com.eas.ereceipt.util.AppConfig;
import com.eas.ereceipt.util.Util;

public class NewReceiptActivity extends Activity {
	public static final int REQUEST_CODE_CAMERA = 101;
	public static final int REQUEST_CODE_SELLECT = 102;
	public static final String JPG_EXT = ".jpg";
	
	private Uri tmpFileUri;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_new_receipt);

	}

	public void onClick(View v) {
		switch (v.getId()) {
		
		case R.id.btnCamera:
			captureImage();
			break;
		case R.id.btnBrowser:
			selectImage();
			break;

		default:
			break;
		}
	}
	
	private void captureImage(){
		if (!Util.isDeviceSupportCamera(getApplicationContext())){
			Toast.makeText(this, R.string.toast_msg_no_camera, Toast.LENGTH_SHORT).show();
			return;
		}
		
		tmpFileUri = getOutputImageFileUri(AppConfig.TEMP_DIRECTORY_NAME);
		
		Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		takePicture.putExtra(MediaStore.EXTRA_OUTPUT, tmpFileUri);
		
		startActivityForResult(takePicture, REQUEST_CODE_CAMERA);
		
	}
	
	private void selectImage(){
		Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
		photoPickerIntent.setType("image/*");
		startActivityForResult(photoPickerIntent, REQUEST_CODE_SELLECT);
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putParcelable("tmpUri", tmpFileUri);
	}
	
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		tmpFileUri = savedInstanceState.getParcelable("tmpUri");
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case REQUEST_CODE_CAMERA:
			if (resultCode == RESULT_OK){
				saveCompressdImg(tmpFileUri, REQUEST_CODE_CAMERA);
				new File(tmpFileUri.getPath()).delete();
			}
			break;
		case REQUEST_CODE_SELLECT:
			if (resultCode == RESULT_OK){
				saveCompressdImg(data.getData(), REQUEST_CODE_SELLECT);
			}
			break;

		default:
			break;
		}
	}
	
	private void saveCompressdImg(Uri src, int reqCode){
		try {
			Bitmap smallBitMap; 
			if (reqCode == REQUEST_CODE_CAMERA) {
				smallBitMap = Util.decodeFile(src.getPath());
			}
			else {
				smallBitMap = Util.decodeStream(this, src);
			}
			FileOutputStream fos = new FileOutputStream(getOutputImageFile(AppConfig.IMAGE_DIRECTORY_NAME));
			smallBitMap.compress(CompressFormat.JPEG, AppConfig.IMG_COMPRESS_QUALITY, fos);
			fos.flush();
			fos.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

	public Uri getOutputImageFileUri(String folder) {
		return Uri.fromFile(getOutputImageFile(folder));
	}
	
	private File getOutputImageFile(String folder) {

		File mediaStorageDir;
		
		if (folder == AppConfig.TEMP_DIRECTORY_NAME){
		// External sdcard location
		mediaStorageDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() 
				+ File.separator + AppConfig.MAIN_DIRECTORY_NAME
				+File.separator + folder);
		} else {
		//Internal
		mediaStorageDir = new File(getFilesDir().getAbsolutePath()
				+ File.separator + AppConfig.MAIN_DIRECTORY_NAME
				+File.separator + folder);
		}
		// Create the storage directory if it does not exist
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.e(folder, "Create dir failed");
				return null;
			}
		}

		// Create a media file name
		String timeStamp = new SimpleDateFormat(AppConfig.SIMPLE_DATE_FORMAT,
				Locale.getDefault()).format(new Date());
		File mediaFile = new File(mediaStorageDir.getPath() + File.separator + timeStamp + JPG_EXT);

		return mediaFile;
	}

}
